<?php

class RssPostManager
{

    public static function GetPostsAsAssoc($limit = -1, $count = 0)
    {
        $sql = 'SELECT
                  rss_info.title                   AS feed_title,
                  rss_info.link 				   AS feed_link,
                  rss_info.description 			   AS feed_description,
                  rss_info.last_modified_date 	   AS feed_last_modified_date,
                  rss_post.title 				   AS post_title,
                  rss_post.description 			   AS post_description,
                  rss_post.link 				   AS post_link,
                  rss_post.author 				   AS post_author,
                  rss_post.creation_date 		   AS post_creation_date,
                  rss_post_image.post_image_id 	   AS image_id,
                  rss_post_image.title 			   AS image_title,
                  rss_post_image.link 			   AS image_link,
                  rss_post_image.image 			   AS image_data,
                  GROUP_CONCAT(rss_category.title) AS category_titles
                FROM
                  rss_post
                LEFT JOIN rss_info ON rss_post.rss_info_id = rss_info.rss_info_id
                LEFT JOIN rss_post_image ON rss_post.post_id = rss_post_image.post_id
                LEFT JOIN rss_post_category ON rss_post_category.rss_post_id = rss_post.post_id
                LEFT JOIN rss_category ON  rss_category.rss_category_id = rss_post_category.rss_category_id
                GROUP BY
                  rss_post.post_id';
        $limitQuery = '';
        if ($limit >= 0)
        {
            $limitQuery .= ' LIMIT ' . $limit;
            $limitQuery .= ($count > 0) ? ', ' . $count : '';
        }
        $sql .= $limitQuery;

        $dataAssoc = Core::DBConn()->Query($sql)->GetAllAssoc();

        foreach ($dataAssoc as $data)
        {
            $rssImageId = $data['image_id'];
            $data['image_path'] = RssSpiderUtils::GenerateImagePathById($rssImageId);
        }

        return $dataAssoc;
    }

    public static function Insert( RssPost $rssPost )
    {
        $tableName = self::GetTableName();
        $sql = "INSERT INTO $tableName
                   (rss_info_id, title, description, content, link, author, creation_date)
                VALUE
                   (@rss_info_id, @title, @description, @content, @link, @author, @creation_date)";

        $params = array
        (
            '@rss_info_id' => $rssPost->GetRssInfoId(),
            '@title' => $rssPost->GetTitle(),
            '@description' => $rssPost->GetDescription(),
            '@content' => $rssPost->GetContent(),
            '@link' => $rssPost->GetPostLink(),
            '@author' => $rssPost->GetAuthor(),
            '@creation_date' => $rssPost->GetCreationDate()
        );

        Core::DBConn()->Query( $sql, Util::QuoteArray($params) );

        $postId = Core::DBConn()->GetLastInsertId();

        $image = $rssPost->GetImage();
        if ( $image != null )
        {
            $image->SetPostId($postId);
            RssPostImageManager::Insert($image);
        }

        $categories = $rssPost->GetCategories();
        RssCategoryManager::InsertRssCategories($postId, $categories);

        $rssPost->SetRssPostId($postId);

        return $postId;
    }

    public static function Update( RssPost $rssPost )
    {
        $tableName = self::GetTableName();
        $sql = "UPDATE $tableName
                SET
                  rss_info_id = @rss_info_id,
                  title = @title,
                  description = @description,
                  content = @content,
                  link = @link,
                  author = @author,
                  creation_date = @creation_date
                WHERE
                  post_id = @post_id";
        $postId = $rssPost->GetRssPostId();

        $params = array
        (
            '@rss_info_id' => $rssPost->GetRssInfoId(),
            '@title' => $rssPost->GetTitle(),
            '@description' => $rssPost->GetDescription(),
            '@content' => $rssPost->GetContent(),
            '@link' => $rssPost->GetPostLink(),
            '@author' => $rssPost->GetAuthor(),
            '@creation_date' => $rssPost->GetCreationDate(),
            '@post_id' => $postId
        );

        Core::DBConn()->Query( $sql, Util::QuoteArray($params) );

        $image = $rssPost->GetImage();
        if ( $image != null )
        {
            $image->SetPostId($postId);
            RssPostImageManager::Insert($image);
        }

        $categories = $rssPost->GetCategories();
        RssCategoryManager::UpdateRssCategories($postId, $categories);

        return $postId;
    }

    public static function Save( RssPost $rssPost )
    {
        $post = array();
        if ($rssPost->GetRssPostId())
        {
            self::Update($rssPost);
            $post['ID'] = $rssPost->GetRssPostId();
        }
        else
        {
            self::Insert($rssPost);
        }
        $post['post_title'] = $rssPost->GetTitle();
        $postContent = $rssPost->GetContent();
        $post['post_content'] = (!empty($postContent)) ? $postContent : $rssPost->GetDescription();
        $post['post_excerpt'] = $rssPost->GetDescription();
        $post['tags_input'] = $rssPost->GetTagTitles();
        $wpPostId = wp_insert_post($post);
        if ($rssPost->GetImage())
        {
            RssPostImageManager::SaveAsThumbnail($rssPost->GetImage(), $wpPostId);
        }
    }

    public static function Delete( $rssPostId )
    {
        $sql = 'DELETE FROM rss_post WHERE post_id = %s';
        Core::DBConn()->Query($sql, Util::Quote($rssPostId));
    }

    public static function GetPostByUrl($url)
    {
        global $wpdb;
        $tableName = self::GetTableName();
        $rssPost = null;
        $sql = "SELECT * FROM $tableName WHERE link = %s";
        $data = $wpdb->get_row($wpdb->prepare($sql, $url), ARRAY_A);
        if ($data)
        {
            $rssPost = self::CreateRssPost($data);
        }
        return $rssPost;
    }

    public static function GetTableName()
    {
        return Util::GetDatabaseTableName("rss_post");
    }

    private static function CreateRssPost( $data )
    {
        $rssPost = new RssPost();

        $rssPost->SetRssInfoId($data['rss_info_id']);
        $rssPost->SetRssPostId($data['post_id']);
        $rssPost->SetTitle($data['title']);
        $rssPost->SetDescription($data['description']);
        $rssPost->SetContent($data['content']);
        $rssPost->SetPostLink($data['link']);
        $rssPost->SetAuthor($data['author']);
        $rssPost->SetCreationDate($data['creation_date']);

        return $rssPost;
    }

}

?>